package service

import (
	"context"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/question/glb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) ListQuestions(ctx context.Context, request *pb.ListQuestionsRequest) (*pb.ListQuestionsResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.ListQuestionsResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager && token.Type == core.UserTypeStudent {
		return &pb.ListQuestionsResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "用户没有权限",
		}}, nil
	}

	questions := make([]models.Question, 0, 128)
	err = glb.DB.Find(&questions, "chapter_uuid = ?", request.GetChapterUUID()).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return listQuestionsRespSvrErr, nil
	}

	questionsResp := make([]*pb.QuestionMoreInfo, 0, len(questions))
	for _, question := range questions {
		questionsResp = append(questionsResp, &pb.QuestionMoreInfo{
			UUID:     question.UUID,
			Question: question.Question.String,
			Analysis: question.Analysis.String,
			Answers: &pb.QuestionAnswers{
				AnswerA: question.AnswerA.String,
				AnswerB: question.AnswerB.String,
				AnswerC: question.AnswerC.String,
				AnswerD: question.AnswerD.String,
				AnswerE: question.AnswerE.String,
				AnswerF: question.AnswerF.String,
				AnswerG: question.AnswerG.String,
				AnswerH: question.AnswerH.String,
			},
			Options: &pb.QuestionOptions{
				IsA:    question.IsA.Bool,
				IsB:    question.IsB.Bool,
				IsC:    question.IsC.Bool,
				IsD:    question.IsD.Bool,
				IsE:    question.IsE.Bool,
				IsF:    question.IsF.Bool,
				IsG:    question.IsG.Bool,
				IsH:    question.IsH.Bool,
				IsTrue: question.IsTrue.Bool,
			},
			Type:         question.Type.Int32,
			Level:        question.Level.Int32,
			AnswerCount:  question.AnswerCount.Int32,
			CorrectCount: question.CorrectCount.Int32,
			ChapterUUID:  question.ChapterUUID.String,
		})
	}

	return &pb.ListQuestionsResponse{
		Status:    &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Questions: questionsResp,
	}, nil
}
